package edu.cmu.cs.stage3.alice.authoringtool.dialog;

import java.awt.BorderLayout;

import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;

import edu.cmu.cs.stage3.alice.authoringtool.util.StyleStream;
import edu.cmu.cs.stage3.alice.authoringtool.util.StyledStreamTextPane;

/**
 * @author Jason Pratt
 */
public class OutputComponent extends javax.swing.JPanel {
	protected JScrollPane scrollPane;
	protected StyledStreamTextPane textPane;
	protected StyleStream stdOutStream;
	protected StyleStream stdErrStream;

	public OutputComponent() {
		guiInit();
		miscInit();
	}

	private void guiInit() {
		setLayout( new java.awt.BorderLayout() );

		textPane = new StyledStreamTextPane();
		scrollPane = new JScrollPane( textPane, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED );

		add( scrollPane, BorderLayout.CENTER );
	}

	private void miscInit() {
		stdOutStream = textPane.getNewStyleStream( textPane.stdOutStyle );
		stdErrStream = textPane.getNewStyleStream( textPane.stdErrStyle );

		// scroll to the end of the output window when new output arrives
		scrollPane.getVerticalScrollBar().getModel().addChangeListener(
				new javax.swing.event.ChangeListener() {
					private int max = 0;
					private javax.swing.JScrollBar scrollBar = scrollPane.getVerticalScrollBar();

					public void stateChanged( javax.swing.event.ChangeEvent e ) {
						final int newMax = ((javax.swing.BoundedRangeModel)e.getSource()).getMaximum();
						if( newMax != max ) {
							javax.swing.SwingUtilities.invokeLater(
									new Runnable() {
										public void run() {
											scrollBar.setValue( newMax );
											max = newMax;
										}
									}
							);
						}
					}
				}
		);
	}

	public edu.cmu.cs.stage3.alice.authoringtool.util.StyledStreamTextPane getTextPane() {
		return textPane;
	}

	public StyleStream getStdOutStream() {
		return stdOutStream;
	}

	public StyleStream getStdErrStream() {
		return stdErrStream;
	}

	public void clear() {
		textPane.setText( "" );
	}
}